/**
 * @开发版权 
 * @项目名称 轻量数据中台(LDMP)
 * @版本信息 v1.0
 * @开发人员 zhous
 * @开发日期 2025-01-17
 * @修订日期
 * @描述  RoleController
 */
package com.ng.sys.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.util.UuidUtil;
import com.ng.sys.model.domain.*;
import com.ng.sys.service.IRole;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Tag(name = "角色管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys/role")
public class RoleController extends Controller{

	@Autowired
	private IRole roleImpl;
	
	
	@Operation(summary = "分页获取角色列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false),
		@Parameter(name = "cur", description = "当前页码", required = true),
		@Parameter(name = "limit", description = "每页数据量", required = true)})
	@TokenRequired
	@GetMapping(value = { "/pages" }, produces = "application/json; charset=utf-8")
	public R<Page<Role>> pages(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {
		String sqlExceptSelect = " from " + Role.TABLE_NAME + "  a WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " and (a.name like '%" + keywords + "%' or a.code like '%" + keywords + "%') ";
		}
		sqlExceptSelect += "  ORDER BY a.sort asc ";
		return R.ok(Role.dao.paginate(cur, limit, "select a.* ", sqlExceptSelect));
	}

	
	@Operation(summary = "保存角色")
	@Parameters({ 
		@Parameter(name = "role", description = "角色", required = true)})
	@TokenRequired
	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Role> save(HttpServletRequest request, @RequestBody Role role) {
		try {
			if (StrKit.notBlank(role.getId())) {
				Role checkRole=Role.dao.findFirst("select * from "+Role.TABLE_NAME+" where id!=? and code=? ",role.getId(),role.getCode());
				if(checkRole!=null) {
					return R.failed("角色编码已存在！");
				}
				role.setUpdateUserId(getUserId(request));
				if (role.update()) {
					return R.ok(role);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				Role checkRole=Role.dao.findFirst("select * from "+Role.TABLE_NAME+" where code=? ",role.getCode());
				if(checkRole!=null) {
					return R.failed("角色编码已存在！");
				}
				
				role.setId(UuidUtil.getUUID());
				role.setCreateUserId(getUserId(request));
				if (role.save()) {
					return R.ok(role);
				} else {
					return R.failed("保存失败.");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Operation(summary = "删除角色")
	@Parameters({ 
		@Parameter(name = "ids", description = "角色id集合(逗号分割)", required = true)})
	@DeleteMapping("/{ids}")
	@TokenRequired
	public R<String> deleteMenu(@PathVariable("ids") String ids) {
		String[] arr=ids.split(",");
		if(ids==null || ids.length()<=0) {
			return R.failed("请选择需要删除的角色.");
		}
		for(String id:arr) {
			roleImpl.delete(id);
		}
		return R.ok();
	}

	@Operation(summary = "获取角色的菜单ID集合")
	@Parameters({ 
		@Parameter(name = "id", description = "角色id", required = true)})
	@GetMapping("/{id}/menuIds")
	public R<List<String>> getRoleMenuIds(@PathVariable("id") String id) {
		List<String> menuIds = roleImpl.getRoleMenuIds(id);
		return R.ok(menuIds);
	}

	@Operation(summary = "分配菜单权限给角色")
	@Parameters({ 
		@Parameter(name = "id", description = "角色id", required = true)})
	@PostMapping("/{id}/menus")
	public R<String> updateRoleMenus(@PathVariable("id") String id, @RequestBody List<String> menuIds) {
		boolean result = roleImpl.updateRoleMenus(id, menuIds);
		if (result) {
			return R.ok();
		} else {
			return R.failed();
		}
	}

	@Operation(summary = "角色下拉列表")
	@TokenRequired
	@GetMapping("/options")
	public R<List<Role>> listRoleOptions(HttpServletRequest request) {
        List<Role> options = Role.dao.find("select * from "+Role.TABLE_NAME+" order by sort asc");
		return R.ok(options);
	}


}
